// pages/mine/mine.js
const app = getApp()
Page({
  /**
   * 页面的初始数据
   */
  data: {
    userInfo: {},
    hasUserInfo: false,
    canIUse: wx.canIUse('button.open-type.getUserInfo'),//判断参数是否在当前版本可用
  },
  //事件处理函数
  onLoad: function () {
    if (app.globalData.userInfo) {
      this.setData({
        userInfo: app.globalData.userInfo,
        hasUserInfo: true
      })
    } else if (this.data.canIUse) {
      // 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
      // 所以此处加入 callback 以防止这种情况
      app.userInfoReadyCallback = res => {
        this.setData({
          userInfo: res.userInfo,
          hasUserInfo: true
        })
      }
    } else {
      // 在没有 open-type=getUserInfo 版本的兼容处理
      wx.getUserInfo({
        success: res => {
          app.globalData.userInfo = res.userInfo
          this.setData({
            userInfo: res.userInfo,
            hasUserInfo: true
          })
        }
      })
    }
  },
  getUserInfo: function (e) {
    console.log(e)
    app.globalData.userInfo = e.detail.userInfo
    this.setData({
      userInfo: e.detail.userInfo,
      hasUserInfo: true
    })
  },
  //关于我们
  tapNews:function(){
    wx.showModal({
      title: '知食分子店铺',
      content: '欢迎广大朋友购买！本店铺专注周边新鲜水果蔬菜等，祝大家使用愉快。',
      success: function (res) {
        if (res.cancel) {
          console.log('用户点击取消')
        } else if (res.confirm) {
          console.log('用户点击确定')
        }
      }
    })
  },
  //订单详情
  tap_order:function(e){
    var id=e.currentTarget.dataset.id;
    wx.navigateTo({
      url: '../order_list/order_list?id='+id,
      success: function(res) {},
      fail: function(res) {},
      complete: function(res) {},
    })
  },
  //收货地址管理功能
  addAddress: function () {
    //调起用户编辑收货地址的原生界面，返回用户选择的地址
    //（就是用户在微信上填写完的地址）
    var that = this;
    wx.chooseAddress({
      success: function (res) {
        console.log(res);
        var addressInfo = {
          name: res.userName,
          mobile: res.telNumber,
          totalDetail: that.setAddress(res)
        };
        that.bindAddress(addressInfo)
        that.submitAddress(res)
      },
      fail: function (err) {
        /*wx.openSetting({
          success: (res) => {
            console.log("授权结果..")
            console.log(res)
            if (!res.authSetting["scope.userInfo"] || !res.authSetting["scope.userLocation"]) {
              applyNotice()
            }
          }
        })*/
      }
    })
  },
  //绑定地址
  bindAddress: function (addressInfo) {
    this.setData({
      addressInfo: addressInfo
    })
  },
  setAddress: function (res) {
    //拼合地址，若微信原生界面存在地址则显示，不存在则显示服务器数据库中的收货地址
    var province = res.provinceName || res.province,
      city = res.cityName || res.city,
      country = res.countyName || res.country,
      detail = res.detailInfo || res.detail;
    var totalDetail = city + country + detail;
    //直辖市，取出省部分
    if (!this.isCenterCity(province)) {
      totalDetail = province + totalDetail;
    };
    return totalDetail;
  },

  /*是否为直辖市*/
  isCenterCity(name) {
    var centerCitys = ['北京市', '天津市', '上海市', '重庆市'],
      flag = centerCitys.indexOf(name) >= 0;
    return flag;
  },

  submitAddress: function (res) {
    wx.request({
      url: 'http://111.230.44.126:88/api/v1/address',
      method: "post",
      data: {
        name: res.userName,
        mobile: res.telNumber,
        city: res.cityName,
        country: res.countyName,
        province: res.provinceName,
        detail: res.detailInfo,
      },
      header: {
        'content-type': 'application/json',
        'token': wx.getStorageSync('token')
      },
      success: function () {
        wx.showToast({
          title: "地址成功保存",
          icon: 'success',
          duration: 2000
        })
      },
      fail: function () {
        wx.showModal({
          title: '获取地址失败',
          content: res.errMsg,
          showCancel: false
        })
      }
    })
  }
})

